import { Component, OnInit, Inject, Injectable } from '@angular/core';
import { CommonService } from 'src/app/core/common/common.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { AlertController, ModalController } from '@ionic/angular';
import { Downloader, DownloadRequest, NotificationVisibility } from '@ionic-native/downloader/ngx';
import { environment } from 'src/environments/environment';
import { FileOpener } from '@ionic-native/file-opener/ngx';

@Component({
  selector: 'app-user-center',
  templateUrl: './user-center.component.html',
  styleUrls: ['./user-center.component.scss'],
})
export class UserCenterComponent implements OnInit {

  constructor(
    private commonService: CommonService,
    private router: Router,
    private alertController: AlertController,
    private downloader: Downloader,
    private fileOpener: FileOpener,
    private modalController: ModalController,
    private http: HttpClient) { }

  data={
    over:0,
    paiche: 0,
    xiehuo: 0,
    zhuanghuo: 0,
    totalMoney:0
  }

  ngOnInit() {}


  /**
   * 退出
   */
  logout() {
    this.commonService.remove();
    this.router.navigate(['login']);
  }

  /**
   * 提示
   */
  onPromot(){
    this.commonService.presentAlertConfirm('功能开发中...');
  }

  /**
   * 意见反馈弹窗
   */
  async presentFeedbackPrompt() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '意见反馈',
      inputs: [
        {
          name: 'title',
          type: 'text',
          placeholder: '请输入标题',
        },
        {
          name: 'content',
          type: 'textarea',
          placeholder: '请输入反馈内容',
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {}
        }, {
          text: '提交',
          handler: (data) => {
            console.log('data:',data);
            if(data.title==='' || data.content===''){
              this.commonService.presentAlertConfirm('标题和反馈内容不能为空');
            }else{
              this.addFeedback(data.title,data.content);
            }
          }
        }
      ]
    });

    await alert.present();
  }

  /**
   * 提交反馈
   */
  addFeedback(title:string,content:string) {
    this.commonService.getToken().then((token) =>{
      const body=`
      {
        "title":"${title}",
        "content":"${content}"
      }`;
      const headerOptions=new HttpHeaders().set('Content-Type','application/json; charset=UTF-8')
      .set('Authorization','Bearer '+token);
      this.http.post('/api/Common/AddFeedback',body,{headers:headerOptions})
      .subscribe((res: any) => {
        this.commonService.presentAlertConfirm(res.message);
      });
    })
  }

  /**
   * 密码修改弹窗
   */
  async presentChangePasswordPrompt() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '密码修改',
      inputs: [
        {
          name: 'oldPassword',
          type: 'password',
          placeholder: '请输入原密码',
        },
        {
          name: 'newPassword',
          type: 'password',
          placeholder: '请输入新密码',
        },
        {
          name: 'repeatPassword',
          type: 'password',
          placeholder: '请再次输入密码',
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {}
        }, {
          text: '确定',
          handler: (data) => {
            console.log('data:',data);
            if(data.oldPassword==='' || data.newPassword==='' || data.repeatPassword===''){
              this.commonService.presentAlertConfirm('需要填写的值不能为空');
            }else if(data.newPassword!==data.repeatPassword){
              this.commonService.presentAlertConfirm('两次输入的密码不一致');
            }else{
              this.changePassword(data.oldPassword,data.newPassword,data.repeatPassword);
            }
          }
        }
      ]
    });

    await alert.present();
  }

  /**
   * 修改密码
   */
  changePassword(oldPassword:string,newPassword:string,repeatPassword:string) {
    this.commonService.getToken().then((token) =>{
      const body=`
      {
        "oldpw":"${oldPassword}",
        "newpw":"${newPassword}",
        "confirmpw":"${repeatPassword}"
      }`;
      const headerOptions=new HttpHeaders().set('Content-Type','application/json; charset=UTF-8')
      .set('Authorization','Bearer '+token);
      this.http.post('/api/UserManage/ModifyPassword',body,{headers:headerOptions})
      .subscribe((res: any) => {
        if (res.code === 1) {
          this.commonService.presentAlertConfirm(res.message);
          this.logout();
        } else {
          this.commonService.presentAlertConfirm(res.message);
        }
      });
    })
  }



// #region App更新

  /**
   * 获取版本号
   */
  getVersion(){
      const version=environment.version;
      // 获取服务器最新版本
      this.commonService.getToken().then((token) =>{
        const headerOptions=new HttpHeaders().set('Content-Type','application/json; charset=UTF-8')
        .set('Authorization','Bearer '+token);
        this.http.get('/api/Common/GetVersion',{headers:headerOptions})
        .subscribe((res: any) => {
          if(res && res.version){
            const newVersion = res.version;
            if(Number(newVersion)>Number(version)){
              this.presentAlertUpdateConfirm(`版本号为：${version}，已经发布新版本：${newVersion}。更新内容：${res.description}`,res.description,newVersion);
            }else{
              this.commonService.presentAlertConfirm(`版本号为：${version}，已经是最新版本。`);
            }
          }else{
            this.commonService.presentAlertConfirm(`版本号为：${version}，已经是最新版本。`);
          }
        });
      })

  }

  /**
   * 更新提醒
   */
  async presentAlertUpdateConfirm(msg: string,description: string,newVersion:string) {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '提醒',
      message: msg,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {}
        }, {
          text: '更新',
          handler: () => {
            this.downloadFile(description,newVersion);
          }
        }
      ]
    });
    await alert.present();
  }

  /**
   * 下载并打开
   */
  downloadFile(description: string,newVersion:string){
    const request: DownloadRequest = {
      uri: `${environment.SERVER_URL}/luyuntong-${newVersion}.apk`,
      title: '陆运通更新',
      description,
      mimeType: '',
      visibleInDownloadsUi: true,
      notificationVisibility: NotificationVisibility.VisibleNotifyCompleted,
      destinationInExternalFilesDir: {
          dirType: 'Downloads',
          subPath: `luyuntong-${newVersion}.apk`
      }
  };
  this.downloader.download(request)
          .then((location: string) => {
              // 打开文件
              this.fileOpener.open(location, 'application/vnd.android.package-archive')
                .then(() => {
                  console.log('File is opened')
                })
                .catch(e => {
                  console.log('Error openening file', e) });
          })
          .catch((error: any) => alert(error));
  }

// #endregion


}
